<template>
  <div v-if="visible" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] flex flex-col">
      <!-- 弹窗头部 -->
      <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800">上传文件</h3>
        <button @click="handleClose" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times"></i>
        </button>
      </div>
      
      <!-- 弹窗内容 -->
      <div class="flex-1 px-6 py-4 overflow-y-auto">
        <!-- 上传区域 -->
        <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-indigo-500 transition-colors mb-6">
          <input
            ref="fileInput"
            type="file"
            multiple
            class="hidden"
            @change="handleFileSelect"
            :accept="allowedFileTypes.join(',')"
          >
          <div class="flex flex-col items-center justify-center">
            <i class="fa fa-cloud-upload text-4xl text-gray-400 mb-3"></i>
            <p class="text-gray-500 mb-2">拖拽文件到此处或点击上传</p>
            <p class="text-sm text-gray-400">支持的文件格式：{{ allowedFileTypesText }}</p>
            <p class="text-sm text-gray-400">单文件最大：{{ maxFileSizeMB }}MB</p>
            <button
              @click="$refs.fileInput.click()"
              class="mt-4 px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors"
            >
              选择文件
            </button>
          </div>
        </div>
        
        <!-- 文件列表 -->
        <div v-if="uploadQueue.length > 0" class="space-y-3 mb-6">
          <h4 class="text-sm font-medium text-gray-700">待上传文件 ({{ uploadQueue.length }})</h4>
          <div v-for="(file, index) in uploadQueue" :key="index" class="flex items-center justify-between p-3 border border-gray-200 rounded-lg">
            <div class="flex items-center">
              <i class="fa" :class="getFileIconClass(file.type)"></i>
              <div class="ml-3">
                <p class="text-sm font-medium text-gray-800 truncate max-w-xs" :title="file.name">{{ file.name }}</p>
                <p class="text-xs text-gray-500">{{ formatFileSize(file.size) }}</p>
              </div>
            </div>
            <div class="flex items-center">
              <button
                @click="removeFile(index)"
                class="text-gray-400 hover:text-red-500 transition-colors"
              >
                <i class="fa fa-times"></i>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 上传选项 -->
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文件分类</label>
            <select v-model="selectedCategory" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
              <option value="banner">轮播图</option>
              <option value="product">产品图片</option>
              <option value="article">文章配图</option>
              <option value="avatar">头像</option>
              <option value="other">其他</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文件说明</label>
            <textarea
              v-model="fileDescription"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              rows="2"
              placeholder="请输入文件说明（可选）"
            ></textarea>
          </div>
        </div>
      </div>
      
      <!-- 弹窗底部 -->
      <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
        <button
          @click="handleClose"
          class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
          :disabled="uploading"
        >
          取消
        </button>
        <button
          @click="startUpload"
          class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors"
          :disabled="uploadQueue.length === 0 || uploading"
        >
          <i v-if="uploading" class="fa fa-spinner fa-spin mr-1"></i>
          {{ uploading ? '上传中...' : '开始上传' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'upload-success'])

// 上传配置
const allowedFileTypes = [
  'image/*',
  'video/mp4', 'video/avi', 'video/mov', 'video/wmv',
  'application/pdf', 'application/msword', 'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
]
const allowedFileTypesText = '图片(jpg, png, gif等)、视频(mp4, avi等)、文档(pdf, doc, xls等)'
const maxFileSizeMB = 10
const maxFileSizeBytes = maxFileSizeMB * 1024 * 1024

// 状态管理
const uploadQueue = reactive([])
const selectedCategory = ref('other')
const fileDescription = ref('')
const uploading = ref(false)

// 处理文件选择
const handleFileSelect = (event) => {
  const files = event.target.files
  if (!files.length) return
  
  Array.from(files).forEach(file => {
    // 检查文件大小
    if (file.size > maxFileSizeBytes) {
      alert(`${file.name} 文件大小超过 ${maxFileSizeMB}MB 限制`)
      return
    }
    
    // 检查文件类型
    const fileType = file.type.split('/')[0]
    if (!['image', 'video', 'application'].includes(fileType)) {
      alert(`${file.name} 文件类型不支持`)
      return
    }
    
    // 添加到上传队列
    uploadQueue.push({
      name: file.name,
      size: file.size,
      type: file.type,
      file: file
    })
  })
  
  // 清空input，允许重复选择同一文件
  event.target.value = ''
}

// 移除文件
const removeFile = (index) => {
  uploadQueue.splice(index, 1)
}

// 开始上传
const startUpload = async () => {
  if (uploadQueue.length === 0) return
  
  uploading.value = true
  
  try {
    // 模拟上传过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 准备上传成功的文件数据
    const uploadedFiles = uploadQueue.map(file => {
      const fileType = file.type.split('/')[0]
      
      // 生成模拟的文件URL
      let mockUrl = ''
      if (fileType === 'image') {
        // 使用随机图片作为示例
        mockUrl = `https://picsum.photos/id/${Math.floor(Math.random() * 1000)}/400/400`
      } else if (fileType === 'video') {
        mockUrl = '#'
      }
      
      return {
        name: file.name,
        type: fileType,
        category: selectedCategory.value,
        size: Math.round(file.size / 1024), // 转换为KB
        url: mockUrl,
        uploadTime: new Date().toISOString(),
        uploadBy: 'admin',
        description: fileDescription.value
      }
    })
    
    // 触发上传成功事件
    emit('upload-success', uploadedFiles)
    
    // 清空上传队列
    uploadQueue.length = 0
    fileDescription.value = ''
    
    // 关闭弹窗
    handleClose()
  } catch (error) {
    console.error('上传失败:', error)
    alert('上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 处理关闭
const handleClose = () => {
  if (!uploading) {
    emit('close')
    // 清空上传队列
    uploadQueue.length = 0
    fileDescription.value = ''
  }
}

// 获取文件图标类名
const getFileIconClass = (fileType) => {
  const type = fileType.split('/')[0]
  if (type === 'image') return 'fa-file-image-o text-green-500'
  if (type === 'video') return 'fa-file-video-o text-blue-500'
  if (type === 'application') {
    if (fileType.includes('pdf')) return 'fa-file-pdf-o text-red-500'
    if (fileType.includes('word') || fileType.includes('doc')) return 'fa-file-word-o text-blue-400'
    if (fileType.includes('excel') || fileType.includes('xls')) return 'fa-file-excel-o text-green-400'
    return 'fa-file-text-o text-gray-500'
  }
  return 'fa-file-o text-gray-500'
}

// 格式化文件大小
const formatFileSize = (sizeBytes) => {
  if (sizeBytes >= 1024 * 1024) {
    return (sizeBytes / (1024 * 1024)).toFixed(2) + ' MB'
  } else if (sizeBytes >= 1024) {
    return (sizeBytes / 1024).toFixed(2) + ' KB'
  }
  return sizeBytes + ' B'
}
</script>

<style scoped>
/* 拖拽样式 */
.border-dashed {
  transition: all 0.3s ease;
}

.border-dashed:hover {
  background-color: rgba(237, 242, 247, 0.5);
}

/* 上传动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.3s ease;
}
</style>